#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''=================================================
@Project -> File   ：FastRiteApi -> get_auth_code
@IDE    ：PyCharm
@Author ：Json
@Date   ：2025/3/20 11:09
@Desc   ：
=================================================='''
import json
import hmac
import hashlib


def sort_dict_case_insensitive(obj):
    """
    递归地对 obj 进行“不区分大小写”的 key 排序，返回新的对象。
    如果你只需要最外层排序，可省略递归。
    """
    if isinstance(obj, dict):
        # 按 key.lower() 排序，得到一个 (key, value) 的列表
        sorted_items = sorted(obj.items(), key=lambda x: x[0].lower())
        new_dict = {}
        for k, v in sorted_items:
            new_dict[k] = sort_dict_case_insensitive(v)
        return new_dict
    elif isinstance(obj, list):
        return [sort_dict_case_insensitive(x) for x in obj]
    else:
        return obj


def generate_authcode_v2(appKey, appSecret, reqTime, data):
    """
    生成 authcode:
      1. 对 data 字段做字典序(不区分大小写)排序并转为 JSON 字符串
      2. 将 appKey, data_json, reqTime 再按照字典序(不区分大小写)进行拼接
      3. 对拼接串做 HmacSHA256 签名，返回小写十六进制结果
    """
    # 第一步：对 data 做不区分大小写的排序
    sorted_data = sort_dict_case_insensitive(data)
    data_json = json.dumps(sorted_data, separators=(',', ':'), ensure_ascii=False)
    # 例如：{"current":1,"outboundOrderNos":"OB069220519008,OB069220519007,OB069220519006","size":10}

    # 第二步：准备参与排序和拼接的 dict（appKey, data_json, reqTime）
    tmp_dict = {
        "appKey": appKey,
        "data": data_json,
        "reqTime": str(reqTime)
    }
    # 根据 key.lower() 做排序，得到拼接顺序
    sorted_keys = sorted(tmp_dict.keys(), key=lambda x: x.lower())

    # 按顺序拼接对应的值
    to_sign_str = "".join(tmp_dict[k] for k in sorted_keys)

    # 第三步：HmacSHA256 签名
    sign_bytes = hmac.new(
        key=appSecret.encode("utf-8"),
        msg=to_sign_str.encode("utf-8"),
        digestmod=hashlib.sha256
    ).hexdigest()

    return sign_bytes


if __name__ == "__main__":
    # 以题目中给的示例进行测试
    appKey_test = "xxxxxx"
    appSecret_test = "xxxxxxx"
    reqTime_test = "1653640516"  # 示例中为字符串也可以
    # data_test = {
    #     "current": 1,
    #     "size": 10,
    #     "outboundOrderNos": "OB069220519008,OB069220519007,OB069220519006"
    # }
    data_test = [{
        "sku": "BM-DET400G01",
        "productCode": "732416595398",
        "productName": "Educator ET-400 Transmitters battery",
        "length": 7,
        "width": 5,
        "height": 2,
        "weight": 0.04,
        "declareNameCn": "Educator ET-400 Transmitters 电池",
        "declareNameEn": "Educator ET-400 Transmitters battery",
        # "customhouseCode": "HS1234.56.78",
        "declarePrice": 1,
        "countryOfOriginName": "CN",
        "dangerousCargo": 4,
        # 可选字段示例
        "productAliasName": "ET-400 battery",
    }]

    # 预期示例 authcode = 31450e8c7603b1b2a4fdb0143740a105d7260cb291c08208b658eabe52f1ec6b
    authcode = generate_authcode_v2(appKey_test, appSecret_test, reqTime_test, data_test)
    print("生成的 authcode:", authcode)
